class User < ActiveRecord::Base
  has_many :added_relations, :foreign_key => "relation_id", :class_name => "Relationship", :dependent => :destroy
  has_many :relations_added, :through => :added_relations
  has_many :recvd_relations, :foreign_key => "user_id", :class_name => "Relation", :dependent => :destroy
  has_many :relations_recvd, :through => :recvd_relations

  validates_presence_of :username, :email
  validates_uniqueness_of :username, :email
  validates_confirmation_of :password
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "Invalid email"  

  attr_reader :password

  def password=(pw)
    @password = pw
    salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp # 2^48 combos
    self.password_salt, self.password_hash =
      salt, Digest::MD5.hexdigest(pw + salt)
  end

  def password_is?(pw)
    Digest::MD5.hexdigest(pw + password_salt) == password_hash
  end

end

